package br.com.consultsystems.persistencia.impl.cadastro;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import br.com.consultsystems.dominio.cadastro.Fornecedor;
import br.com.consultsystems.persistencia.spec.AbstractAdministradoraRepository;
import br.com.consultsystems.persistencia.spec.cadastro.FornecedorPersistencia;

@Stateless(name = "fornecedorPersistencia")
public class FornecedorPersistenciaImpl extends
		AbstractAdministradoraRepository<Fornecedor> implements
		FornecedorPersistencia {

	protected FornecedorPersistenciaImpl() {
		super(Fornecedor.class);
	}

	@Override
	public List<Fornecedor> retrieveAll() {
		return retrieveByCriteria(null);
	}

	@Override
	public List<Fornecedor> retrieveByFornecedor(String fantasia) throws Exception {

		final EntityManager em = getEntityManager();
		final CriteriaBuilder criteriaBuilder = createCriteriaBuilder();
		final CriteriaQuery<Fornecedor> criteriaQuery = createCriteriaQuery(criteriaBuilder);
		final Root<Fornecedor> root = createRoot(criteriaQuery);
		
		/* Repository -> Apenas pesquias as informações no banco de dados
		 * Filtro por codigo */
		final Path<String> pathFantasia = root.get("fantasia");
		final Predicate predicateFantasia = criteriaBuilder.like(pathFantasia, "%"+fantasia+"%");
		criteriaQuery.where(predicateFantasia);
		criteriaQuery.orderBy(criteriaBuilder.asc(pathFantasia));
		
		final TypedQuery<Fornecedor> typedQuery = em.createQuery(criteriaQuery);
		return typedQuery.getResultList();
	}

	@Override
	public List<Fornecedor> retrieveByGrupo(String razaoSocial) throws Exception {

		final EntityManager em = getEntityManager();
		final CriteriaBuilder criteriaBuilder = createCriteriaBuilder();
		final CriteriaQuery<Fornecedor> criteriaQuery = createCriteriaQuery(criteriaBuilder);
		final Root<Fornecedor> root = createRoot(criteriaQuery);
		
		/* Repository -> Apenas pesquias as informações no banco de dados
		 * Filtro por codigo */
		final Path<String> pathRazaoSocial = root.get("razaoSocial");
		final Predicate predicateRazaoSocial = criteriaBuilder.like(pathRazaoSocial, "%"+razaoSocial+"%");
		criteriaQuery.where(predicateRazaoSocial);
		criteriaQuery.orderBy(criteriaBuilder.asc(pathRazaoSocial));
		
		final TypedQuery<Fornecedor> typedQuery = em.createQuery(criteriaQuery);
		return typedQuery.getResultList();
	}
	
}
